package com.example.interceptor;

import com.example.entity.user.UserInfo;
import com.example.mapper.AccountMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class AuthorizeInterceptor implements HandlerInterceptor {

    @Resource
    private AccountMapper accountMapper;

    public AuthorizeInterceptor(AccountMapper accountMapper) {
        this.accountMapper = accountMapper;
    }

    public AuthorizeInterceptor() {
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        SecurityContext securityContext = SecurityContextHolder.getContext();
        Authentication authentication = securityContext.getAuthentication();
        User user = (User) authentication.getPrincipal();
        String username = user.getUsername();
        UserInfo userInfo = accountMapper.findUserInfoByNameOrEmail(username);
        request.getSession().setAttribute("userInfo",userInfo);
        return true;
    }
}
